package com.mock.ems.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPool;

import java.lang.reflect.Field;

public class RedisPoolManager {

    private static final Logger logger = LoggerFactory.getLogger(RedisPoolManager.class);
    public static void init(RedisConfig redisConfig) {

        try {
            Class<RedisSingleHandler> redisSingleHandlerClazz = RedisSingleHandler.class;
            Field jedisPoolField = redisSingleHandlerClazz.getDeclaredField("pool");
            if (null == jedisPoolField) throw new RuntimeException("can not init jedis pool");
            JedisPool jedisPool = null;
            if (null == redisConfig.getPassword()) {
                jedisPool = new JedisPool(redisConfig.getJedisPoolConfig(), redisConfig.getRedisHost(), redisConfig.getRedisPort());
            }else {
                jedisPool = new JedisPool(redisConfig.getJedisPoolConfig(), redisConfig.getRedisHost(), redisConfig.getRedisPort(),
                        1500, redisConfig.getPassword());
            }
            jedisPoolField.setAccessible(true);
            jedisPoolField.set(null, jedisPool);

        }catch (Exception e) {
            logger.error(e.getLocalizedMessage(),e);
            throw new RuntimeException(e.getCause());
        }
        logger.info("redis init successfully!");
    }
}
